package com.face.face.activity;

import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.face.face.R;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.zhy.autolayout.AutoLayoutActivity;

import java.util.ArrayList;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CALL_PHONE;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_CONTACTS;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class BaseActivity extends AutoLayoutActivity {

    public final static int FAILED = 500;
    public final static int SUCCESS = 200;

    private String title;
    private DialogPlus dialog;
    private DialogPlus msgdialog;

    public void fullscreen() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        fullscreen();
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    public void showLoadingDialog() {
        dialog = DialogPlus.newDialog(this)
                .setOnDismissListener(onDismissListener)
                .setInAnimation(R.anim.alpha_in)
                .setOutAnimation(R.anim.alpha_out)
                .setContentHolder(new ViewHolder(R.layout.loading))
                .setExpanded(false)
                .setGravity(Gravity.CENTER)
                .setContentWidth(ViewGroup.LayoutParams.WRAP_CONTENT)  // or any custom width ie: 300
                .setContentHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
                .setContentBackgroundResource(Color.parseColor("#00000000"))
                .setCancelable(true)
                .create();
        dialog.show();
    }

    OnDismissListener onDismissListener = new OnDismissListener() {
        @Override
        public void onDismiss(DialogPlus dialog) {
            showMessageDialog();
        }
    };

    String msg = "完成";

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void showMessageDialog() {
        msgdialog = DialogPlus.newDialog(this)
                .setContentHolder(new ViewHolder(R.layout.message))
                .setExpanded(false)
                .setGravity(Gravity.BOTTOM)
                .setContentWidth(ViewGroup.LayoutParams.WRAP_CONTENT)  // or any custom width ie: 300
                .setContentHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
                .setContentBackgroundResource(Color.parseColor("#00000000"))
                .setCancelable(true)
                .create();
        TextView msgtv = (TextView) msgdialog.getHolderView().findViewById(R.id.msg);
        msgtv.setText(msg);
        msgdialog.show();
    }

    public void dismissMsgDialog() {
        if (msgdialog != null) {
            msgdialog.dismiss();
            msgdialog = null;
        }
    }

    public void dismissLoadingDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    /******************************************************************************************/

    private final static int COARSE_LOCATION_RESULT = 100;
    private final static int FINE_LOCATION_RESULT = 101;
    private final static int CALL_PHONE_RESULT = 102;
    private final static int CAMERA_RESULT = 103;
    private final static int READ_CONTACTS_RESULT = 104;
    private final static int WRITE_EXTERNAL_RESULT = 105;
    private final static int RECORD_AUDIO_RESULT = 106;
    private final static int ALL_PERMISSIONS_RESULT = 107;
    private int sign;
    private ArrayList<String> permissionsToRequest;
    private ArrayList<String> permissionsRejected;
    private SharedPreferences sharedPreferences;

    @TargetApi(Build.VERSION_CODES.M)
    protected void initPermissions() {
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        int resultCode = 0;
        ArrayList<String> permissions = new ArrayList<>();
        permissions.add(WRITE_EXTERNAL_STORAGE);
        resultCode = WRITE_EXTERNAL_RESULT;
        permissions.add(ACCESS_FINE_LOCATION);
        permissions.add(ACCESS_COARSE_LOCATION);
        permissions.add(CAMERA);
        permissions.add(READ_CONTACTS);
        permissions.add(RECORD_AUDIO);
        permissions.add(CALL_PHONE);
        permissions.add(WRITE_EXTERNAL_STORAGE);

        //filter out the permissions we have already accepted
        permissionsToRequest = findUnAskedPermissions(permissions);
        //get the permissions we have asked for before but are not granted..
        //we will store this in a global list to access later.
        permissionsRejected = findRejectedPermissions(permissions);

        if (permissionsToRequest.size() > 0) {//we need to ask for permissions
            //but have we already asked for them?
            requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), resultCode);
            //mark all these as asked..
            for (String perm : permissionsToRequest) {
                markAsAsked(perm);
            }
        } else {
            //show the success banner
            if (permissionsRejected.size() < permissions.size()) {
            }

            if (permissionsRejected.size() > 0) {

            }
        }
    }

    /**
     * This is the method that is hit after the user accepts/declines the
     * permission you requested. For the purpose of this example I am showing a success header
     * when the user accepts the permission and a snackbar when the user declines it.  In your application
     * you will want to handle the accept/decline in a way that makes sense.
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {
            case FINE_LOCATION_RESULT:
                if (hasPermission(ACCESS_FINE_LOCATION)) {
                } else {
                    permissionsRejected.add(ACCESS_FINE_LOCATION);
                }
                break;
            case COARSE_LOCATION_RESULT:
                if (hasPermission(ACCESS_COARSE_LOCATION)) {
                } else {
                    permissionsRejected.add(ACCESS_COARSE_LOCATION);
                }
                break;
            case CALL_PHONE_RESULT:
                if (hasPermission(CALL_PHONE)) {
                } else {
                    permissionsRejected.add(CALL_PHONE);
                }
                break;
            case CAMERA_RESULT:
                if (hasPermission(CAMERA)) {
                } else {
                    permissionsRejected.add(CAMERA);
                }
                break;
            case READ_CONTACTS_RESULT:
                if (hasPermission(READ_CONTACTS)) {
                } else {
                    permissionsRejected.add(READ_CONTACTS);
                }
                break;
            case WRITE_EXTERNAL_RESULT:
                if (hasPermission(WRITE_EXTERNAL_STORAGE)) {
                } else {
                    permissionsRejected.add(WRITE_EXTERNAL_STORAGE);
                }
                break;
            case RECORD_AUDIO_RESULT:
                if (hasPermission(RECORD_AUDIO)) {
                } else {
                    permissionsRejected.add(RECORD_AUDIO);
                }
                break;
            case ALL_PERMISSIONS_RESULT:
                boolean someAccepted = false;
                boolean someRejected = false;
                for (String perms : permissionsToRequest) {
                    if (hasPermission(perms)) {
                        someAccepted = true;
                    } else {
                        someRejected = true;
                        permissionsRejected.add(perms);
                    }
                }

                if (permissionsRejected.size() > 0) {
                    someRejected = true;
                }
                break;
        }

    }

    /**
     * This method is used to determine the permissions we do not have accepted yet and ones that we have not already
     * bugged the user about.  This comes in handle when you are asking for multiple permissions at once.
     *
     * @param wanted
     * @return
     */
    private ArrayList<String> findUnAskedPermissions(ArrayList<String> wanted) {
        ArrayList<String> result = new ArrayList<String>();

        for (String perm : wanted) {
            if (!hasPermission(perm) && shouldWeAsk(perm)) {
                result.add(perm);
            }
        }

        return result;
    }

    /**
     * this will return us all the permissions we have previously asked for but
     * currently do not have permission to use. This may be because they declined us
     * or later revoked our permission. This becomes useful when you want to tell the user
     * what permissions they declined and why they cannot use a feature.
     *
     * @param wanted
     * @return
     */
    private ArrayList<String> findRejectedPermissions(ArrayList<String> wanted) {
        ArrayList<String> result = new ArrayList<String>();

        for (String perm : wanted) {
            if (!hasPermission(perm) && !shouldWeAsk(perm)) {
                result.add(perm);
            }
        }

        return result;
    }

    /**
     * method to determine whether we have asked
     * for this permission before.. if we have, we do not want to ask again.
     * They either rejected us or later removed the permission.
     *
     * @param permission
     * @return
     */
    private boolean shouldWeAsk(String permission) {
        return (sharedPreferences.getBoolean(permission, true));
    }

    /**
     * method that will return whether the permission is accepted. By default it is true if the user is using a device below
     * version 23
     *
     * @param permission
     * @return
     */
    @TargetApi(Build.VERSION_CODES.M)
    private boolean hasPermission(String permission) {
        if (canMakeSmores()) {
            return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
        }
        return true;
    }

    /**
     * Just a check to see if we have marshmallows (version 23)
     *
     * @return
     */
    private boolean canMakeSmores() {
        return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
    }

    /**
     * we will save that we have already asked the user
     *
     * @param permission
     */
    private void markAsAsked(String permission) {
        sharedPreferences.edit().putBoolean(permission, false).apply();
    }

}